import config from './config'

import {encrypt,decrypt} from './crypto.js'

export default async function request(opt) {
	opt = opt || {};
	opt.url = opt.url || '';
	opt.data = opt.data || null;
	opt.method = opt.method || 'GET';
	console.log("请求接口：",opt.url)
	//请求报文加密
	if(config.isEncrypt &&  opt.method != 'GET'){
		//当前时间戳
		let timestamp = Date.now();
		opt.data.timestamp = timestamp
		if(opt.data){
			const jsonStr = JSON.stringify(opt.data)
			console.log("请求报文：",jsonStr)
			const encrptData = encrypt(jsonStr,config.aesKey)
			opt.data = encrptData
		}
	}
	let otherParam = {};
	if (!opt.responseType) {
		opt.header = opt.header || {
			"Content-Type": "application/x-www-form-urlencoded",			
		};
		otherParam.dataType = 'json'
	} else {
		otherParam.responseType = opt.responseType;
		if (opt.dataType) {
			otherParam.dataType = opt.dataType
		}
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: config.apiUrl + opt.url,
			data: opt.data,
			method: opt.method,
			header: opt.header,
			...otherParam,
			success: res => {
				let rspData = res.data
				if(config.isEncrypt){
					rspData = JSON.parse(decrypt(res.data,config.aesKey))
					console.log("响应报文：",rspData)
				}
				const code = rspData.code
				if(code === 200){
					resolve(rspData);
				}else{
					reject(rspData);
				}
			},
			fail: err => {
				reject(err);
			},
			complete: (res) => {}
		})
	})

}